package com.training.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.base.BaseActivity;
import com.training.adapter.AudioAdapter;
import com.training.adapter.FragmentAdapter;
import com.training.bean.Audio;
import com.training.bean.Course;
import com.training.bean.CourseContent;
import com.training.databinding.ActivityCourseContentBinding;
import com.training.fragment.CourseContentFragment;
import com.training.net.Constant;
import com.training.net.HttpResponse;
import com.training.net.NetCallback;
import com.training.player.PlayerService;

import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.training.util.ToastyUtil;
import com.training.utils.DensityUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CourseContentActivity extends BaseActivity<ActivityCourseContentBinding> {
    private Course course;
    ;
    private FragmentAdapter adapter;
    private ArrayList<Fragment> fragments;
    private int currentPosition = 0;
    private PlayerService playerService;
    private boolean isServiceBound = false;


    private List<Audio> currentAudioList;
    private int currentAudioIndex = 0;
    private AudioAdapter spinnerAdapter;

    // 添加播放状态变化广播接收器
    private BroadcastReceiver playbackStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (PlayerService.ACTION_PLAYBACK_STATE_CHANGED.equals(intent.getAction())) {
                boolean isPlaying = intent.getBooleanExtra("isPlaying", false);
                // 根据播放状态更新播放按钮的图标
                updatePlayButtonIcon(isPlaying);
            }
        }
    };

    // 服务连接
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PlayerService.LocalBinder binder = (PlayerService.LocalBinder) service;
            playerService = binder.getService();
            isServiceBound = true;
            // 注册播放状态变化广播接收器
            ContextCompat.registerReceiver(context, playbackStateReceiver, new IntentFilter(PlayerService.ACTION_PLAYBACK_STATE_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBound = false;
        }
    };

    @Override
    public ActivityCourseContentBinding binding() {
        return ActivityCourseContentBinding.inflate(getLayoutInflater());
    }

    @Override
    public void onCreated(Bundle savedInstanceState) {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras == null) {
            finish();
            return;
        }
        course = (Course) extras.getSerializable("course");

        mBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 初始化Spinner
        initAudioSpinner();

        // 绑定播放服务
        Intent serviceIntent = new Intent(this, PlayerService.class);
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

        mBinding.last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter != null && currentPosition > 0) {
                    currentPosition--;
                    mBinding.contentVp.setCurrentItem(currentPosition);
                    updatePlayButtonState();
                }
            }
        });

        mBinding.next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter != null && currentPosition < fragments.size() - 1) {
                    currentPosition++;
                    mBinding.contentVp.setCurrentItem(currentPosition);
                    updatePlayButtonState();
                }
            }
        });

        mBinding.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter != null) {
                    // 切换播放/暂停状态
                    togglePlayback();
                }
            }
        });

        mBinding.rebroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter != null) {
                    // 重新播放当前内容
                    rebroadcastCurrentContent();
                }
            }
        });
        refreshUI();
        loadData();
    }

    @Override
    public void loadData() {
        dc.getAllCourseContent(course.id, new NetCallback<HttpResponse<ArrayList<CourseContent>>>() {
            @Override
            public void onError(int code, String message) {
                ToastyUtil.showError(context, message, Toast.LENGTH_SHORT, true);
            }

            @Override
            public void onSuccess(HttpResponse<ArrayList<CourseContent>> response) {
                createData(response.data);
            }

            @Override
            public void onFinally() {

            }
        });
    }

    @Override
    public void refreshUI() {
        mBinding.toolbar.setTitle(course.title);
    }

    private void createData(ArrayList<CourseContent> data) {
        mBinding.layoutBt.setVisibility(View.VISIBLE);
        fragments = new ArrayList<>();
        for (CourseContent courseContent : data) {
            CourseContentFragment fragment = new CourseContentFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("courseContent", courseContent);
            bundle.putInt("courseSize", data.size());
            bundle.putInt("courseIndex", data.indexOf(courseContent));
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        adapter = new FragmentAdapter(this, fragments);
        mBinding.contentVp.setAdapter(adapter);

        mBinding.contentVp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentPosition = position;
                updatePlayButtonState();
                // 页面切换时重置音频列表
                loadCurrentAudioList();
                // 页面切换时自动播放当前Fragment的音频
                autoPlayCurrentContent();
            }
        });

        // 初始化播放按钮状态
        updatePlayButtonState();
        // 加载当前音频列表
        loadCurrentAudioList();
    }

    /**
     * 更新播放按钮状态
     */
    private void updatePlayButtonState() {
        if (fragments == null || fragments.isEmpty()) return;

        // 如果是第一个内容，禁用上一个按钮
        mBinding.last.setEnabled(currentPosition > 0);

        // 如果是最后一个内容，禁用下一个按钮
        mBinding.next.setEnabled(currentPosition < fragments.size() - 1);
    }

    /**
     * 更新播放按钮图标
     */
    private void updatePlayButtonIcon(boolean isPlaying) {
        if (isPlaying) {
            mBinding.play.setImageResource(com.training.R.mipmap.icon_pause);
        } else {
            mBinding.play.setImageResource(com.training.R.mipmap.icon_play);
        }
    }

    /**
     * 初始化音频选择下拉菜单
     */
    private void initAudioSpinner() {
        spinnerAdapter = new AudioAdapter(context);
        mBinding. audioSpinner.setAdapter(spinnerAdapter);
        mBinding.audioSpinner.setDropDownVerticalOffset(DensityUtils.dp2px(context, -70));
        mBinding.audioSpinner.setDropDownHorizontalOffset(DensityUtils.dp2px(context, 24));
        // 设置Spinner选择监听器
        mBinding.audioSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 当用户选择不同的音频时，更新当前音频索引并播放
                if (position != currentAudioIndex) {
                    currentAudioIndex = position;
                    playCurrentContent();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选择任何项目时不执行操作
            }
        });
    }

    /**
     * 更新音频列表下拉菜单
     */
    private void updateAudioSpinner() {

        if (currentAudioList != null && !currentAudioList.isEmpty()) {
            // 启用Spinner
            mBinding.audioSpinner.setEnabled(true);
            // 通知适配器数据已更改
            spinnerAdapter.notifyDataSetChanged();
            // 默认选择第一个音频
            mBinding.audioSpinner.setSelection(0);
        } else {
            spinnerAdapter.notifyDataSetChanged();
            mBinding.audioSpinner.setSelection(0);
            mBinding.audioSpinner.setEnabled(false);
        }
    }

    /**
     * 加载当前页面的音频列表
     */
    private void loadCurrentAudioList() {
        if (fragments != null && !fragments.isEmpty() && currentPosition < fragments.size()) {
            CourseContentFragment fragment = (CourseContentFragment) fragments.get(currentPosition);
            CourseContent courseContent = fragment.getCourseContent();
            if (courseContent != null && courseContent.audios != null) {
                currentAudioList = courseContent.audios;
                spinnerAdapter.setData(courseContent.audios);
                currentAudioIndex = 0;
                // 更新音频下拉菜单
                updateAudioSpinner();
            }
        }
    }

    /**
     * 播放当前内容
     */
    private void playCurrentContent() {
        if (currentAudioList == null || currentAudioList.isEmpty()) {
            ToastyUtil.showInfo(context, "当前内容没有音频", Toast.LENGTH_SHORT, true);
            return;
        }

        if (currentAudioIndex >= currentAudioList.size()) {
            currentAudioIndex = 0;
        }

        // 更新Spinner的选择状态
        mBinding.audioSpinner.setSelection(currentAudioIndex);

        Audio audio = currentAudioList.get(currentAudioIndex);
        if (audio != null && audio.audio_url != null && !audio.audio_url.isEmpty()) {
            // 检查音频URL是否可访问
            checkAudioUrlAndPlay(audio);
        } else {
            ToastyUtil.showWarning(context, "音频地址无效", Toast.LENGTH_SHORT, true);
        }
    }

    /**
     * 检查音频URL并播放
     *
     * @param audio 音频对象
     */
    private void checkAudioUrlAndPlay(Audio audio) {
        new Thread(() -> {
            try {
                // 检查URL是否可访问
                URL url = new URL(audio.audio_url);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("HEAD");
                connection.setConnectTimeout(5000); // 5秒超时
                connection.connect();
                int responseCode = connection.getResponseCode();
                connection.disconnect();

                // 如果响应码是200表示可访问，或者405（方法不允许）也认为服务器存在该资源
                if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
                    runOnUiThread(() -> {
                        if (isServiceBound && playerService != null) {
                            playerService.playMedia(audio.audio_url);
                            // 使用handler发送消息到主线程显示Toast
//                            mainHandler.post(() -> Toasty.info(context, "正在播放: " + audio.name, Toast.LENGTH_SHORT, true).show());
                        } else {
                            // 如果服务未绑定，尝试通过Intent启动
                            Intent intent = new Intent(this, PlayerService.class);
                            intent.putExtra("audio_url", audio.audio_url);
                            startService(intent);
//                            mainHandler.post(() -> Toasty.info(context, "开始播放: " + audio.name, Toast.LENGTH_SHORT, true).show());
                        }
                    });
                } else {
                    // 即使HTTP检查失败，也尝试播放，因为某些服务器可能阻止HEAD请求
                    runOnUiThread(() -> {
                        if (isServiceBound && playerService != null) {
                            playerService.playMedia(audio.audio_url);
//                            mainHandler.post(() -> Toasty.info(context, "正在播放: " + audio.name, Toast.LENGTH_SHORT, true).show());
                        } else {
                            // 如果服务未绑定，尝试通过Intent启动
                            Intent intent = new Intent(this, PlayerService.class);
                            intent.putExtra("audio_url", audio.audio_url);
                            startService(intent);
//                            mainHandler.post(() -> Toasty.info(context, "开始播放: " + audio.name, Toast.LENGTH_SHORT, true).show());
                        }
                    });
                }
            } catch (Exception e) {
                // 网络检查失败时，仍然尝试播放
                runOnUiThread(() -> {
                    if (isServiceBound && playerService != null) {
                        playerService.playMedia(audio.audio_url);
//                        mainHandler.post(() -> Toasty.info(context, "正在播放: " + audio.name, Toast.LENGTH_SHORT, true).show());
                    } else {
                        // 如果服务未绑定，尝试通过Intent启动
                        Intent intent = new Intent(this, PlayerService.class);
                        intent.putExtra("audio_url", audio.audio_url);
                        startService(intent);
//                        mainHandler.post(() -> Toasty.info(context, "开始播放: " + audio.name, Toast.LENGTH_SHORT, true).show());
                    }
                });
            }
        }).start();
    }

    /**
     * 重新播放当前内容
     */
    private void rebroadcastCurrentContent() {
        // 重置音频索引并播放
        currentAudioIndex = 0;
        playCurrentContent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isServiceBound) {
            unbindService(serviceConnection);
            isServiceBound = false;
        }
        // 注销播放状态变化广播接收器
        try {
            unregisterReceiver(playbackStateReceiver);
        } catch (IllegalArgumentException e) {
            // 接收器未注册，忽略异常
        }
    }

    /**
     * 切换播放/暂停状态
     */
    private void togglePlayback() {
        if (isServiceBound && playerService != null) {
            if (playerService.isPlaying()) {
                // 如果正在播放，则暂停
                playerService.pauseMedia();
            } else {
                // 如果未播放，则继续播放当前内容或开始播放
                playCurrentContent();
            }
        } else {
            // 如果服务未绑定，尝试通过Intent启动播放
            playCurrentContent();
        }
    }

    /**
     * 页面切换时自动播放当前内容
     */
    private void autoPlayCurrentContent() {
        // 检查是否已绑定服务
        if (isServiceBound && playerService != null) {
            // 检查当前Fragment是否有音频列表
            if (currentAudioList != null && !currentAudioList.isEmpty()) {
                // 当前Fragment有音频，自动播放第一个音频
                currentAudioIndex = 0;
                mBinding.audioSpinner.setSelection(0); // 更新Spinner选择
                playCurrentContent();
            } else {
                // 当前Fragment没有音频，暂停正在播放的音频
                if (playerService.isPlaying()) {
                    playerService.pauseMedia();
                }
            }
        }
    }
}